<template>
  <div class="agv-position-container">
    <n-card :bordered="false">
      <!-- 地图/位置显示区域 -->
      <!-- <div
        class="map-container"
        @wheel.prevent="handleWheel"
        @mousedown="handleMouseDown"
        @mousemove="handleMouseMove"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseUp"
      >
        <div class="map-area" ref="mapArea" :style="mapTransform">
          
          <div class="map-background">
            
            <div
              v-for="station in stations"
              :key="station.id"
              :class="['station', `station-${station.type.replace(/\s+/g, '-')}`]"
              :style="{
                  top: `${station.y / 100}%`,
                  left: `${station.x / 100}%`,
                  transform: `scale(${1/scale})`
                }"
              :title="`${station.name}: ${station.type}`"
            >{{ station.name }}</div>

            <div
              v-for="agv in agvPositions"
              :key="agv.car_index"
              class="agv-marker"
              :style="{
                  top: `${agv.y / 100}%`,
                  left: `${agv.x / 100}%`,
                  background: agv.is_connected ? 'green' : 'gray',
                  transform: `translate(-50%, -50%) scale(${1/scale})`
                }"
              :title="`AGV ${agv.car_index}: ${agv.status}`"
            >{{ agv.car_index }}</div>
          </div>
        </div>
      </div> -->

      <!-- 底部控制区 -->
      <!-- <n-flex justify="between" align="center" class="control-bar">
        <n-space>
          <n-button @click="zoomIn">放大</n-button>
          <n-button @click="zoomOut">缩小</n-button>
          <n-button @click="resetZoom">重置</n-button>
          <n-tag type="info">缩放级别: {{ scale.toFixed(2) }}</n-tag>
        </n-space>
        <n-space>
          <n-tag type="info">刷新间隔: {{ refreshInterval }}ms</n-tag>
          <n-select v-model:value="refreshInterval" :options="intervalOptions" @update:value="handleIntervalChange" style="width: 100px;" />
          <n-button type="primary" :loading="loading" @click="fetchAGVPositions">手动刷新</n-button>
        </n-space>
      </n-flex> -->

      <!-- 数据表格 -->
      <n-data-table :columns="columns" :data="agvPositions" class="data-table" />
    </n-card>
  </div>
</template>

  <script setup>
import { ref, onMounted, onUnmounted, h, computed } from "vue";
import { NCard, NFlex, NTag, NSelect, NButton, NDataTable, NSpace, useMessage } from "naive-ui";
import axios from "axios";
import { API_URLS } from '../../utils/apiConfig';

const message = useMessage();

// 状态管理
const loading = ref(false);
const agvPositions = ref([]);
const stations = ref([]);
const refreshInterval = ref(1000); // 默认1秒刷新一次
const intervalId = ref(null);

// 缩放相关状态
const scale = ref(1);
const minScale = ref(0.9);
const maxScale = ref(10);
const offsetX = ref(0);
const offsetY = ref(0);
const isDragging = ref(false);
const lastMouseX = ref(0);
const lastMouseY = ref(0);
const mapArea = ref(null);

// 刷新间隔选项
const intervalOptions = [
  { label: "1秒", value: 1000 },
  { label: "3秒", value: 3000 },
  { label: "5秒", value: 5000 },
  { label: "10秒", value: 10000 },
];

// 使用配置文件中的API地址
const AGV_POSITION_API = API_URLS.agv.position;
const STATIONS_API = API_URLS.map_node.all;

// 计算地图变换样式
const mapTransform = computed(() => ({
  transform: `scale(${scale.value}) translate(${offsetX.value / scale.value}px, ${offsetY.value / scale.value}px)`,
  transition: isDragging.value ? "none" : "transform 0.2s ease",
}));

// 约束地图位置，防止内容被拖出框外，缩小时强制居中
const constrainMapPosition = () => {
  if (!mapArea.value) return;

  const containerRect = mapArea.value.parentElement.getBoundingClientRect();
  const mapWidth = containerRect.width;
  const mapHeight = containerRect.height;

  // 当缩小时（scale < 1），强制内容居中
  if (scale.value < 1) {
    offsetX.value = 0;
    offsetY.value = 0;
  } else {
    // 当地图放大时（scale >= 1），允许一定范围的拖动，但限制边界
    const maxOffsetX = (mapWidth * (scale.value - 1)) / 2;
    const maxOffsetY = (mapHeight * (scale.value - 1)) / 2;

    // 应用边界限制
    offsetX.value = Math.max(-maxOffsetX, Math.min(maxOffsetX, offsetX.value));
    offsetY.value = Math.max(-maxOffsetY, Math.min(maxOffsetY, offsetY.value));
  }
};

// 表格列定义
const columns = [
  { title: "AGV编号", key: "car_index" },
  { title: "X坐标", key: "x" },
  { title: "Y坐标", key: "y" },
  { title: "角度", key: "angle" },
  { title: "状态", key: "status" },
  { title: "速度", key: "speed" },
  { title: "电池电量", key: "battery" },
  { title: "最后更新", key: "updated_at" },
  {
    title: "连接状态",
    key: "connection",
    render(row) {
      return h(NTag, { type: row.is_connected ? "success" : "error" }, { default: () => (row.is_connected ? "已连接" : "断开") });
    },
  },
  { title: "虚拟设备", key: "simulation" },
];

// 获取AGV位置数据
const fetchAGVPositions = async () => {
  loading.value = true;
  try {
    const response = await axios.get(AGV_POSITION_API, {}, { params: {} });

    if (response.data.code === 200) {
      agvPositions.value = response.data.data;
      message.success("数据刷新成功");
    } else {
      message.error(`获取数据失败: ${response.data.msg || "未知错误"}`);
    }
  } catch (error) {
    message.error(`网络错误: 无法获取AGV位置数据 (${error.message})`);
    console.error("获取AGV位置失败:", error);
  } finally {
    loading.value = false;
  }
};

// 处理刷新间隔变更
const handleIntervalChange = () => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }
  startAutoRefresh();
};

// 启动自动刷新
const startAutoRefresh = () => {
  intervalId.value = setInterval(fetchAGVPositions, refreshInterval.value);
};

// 获取站点数据
const fetchStations = async () => {
  try {
    const response = await axios.get(STATIONS_API, { params: {} });

    if (response.data.code === 200) {
      stations.value = response.data.data;
    } else {
      message.error(`获取站点数据失败: ${response.data.msg || "未知错误"}`);
    }
  } catch (error) {
    message.error(`网络错误: 无法获取站点数据 (${error.message})`);
    console.error("获取站点数据失败:", error);
  }
};

// 组件挂载时执行
onMounted(() => {
  fetchAGVPositions();
  fetchStations(); // 加载站点数据
  startAutoRefresh();
  // 确保地图加载后应用边界限制
  setTimeout(() => {
    constrainMapPosition();
  }, 100);
});

// 组件卸载时清理
onUnmounted(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }
});

// 处理鼠标滚轮事件 - 缩放（以鼠标位置为中心）
const handleWheel = (event) => {
  event.preventDefault();
  const delta = event.deltaY > 0 ? -0.1 : 0.1;
  const newScale = Math.max(minScale.value, Math.min(maxScale.value, scale.value + delta));

  // 计算鼠标在地图容器中的位置（相对于容器左上角）
  const rect = mapArea.value.getBoundingClientRect();
  const mouseX = event.clientX - rect.left - rect.width / 2;
  const mouseY = event.clientY - rect.top - rect.height / 2;

  // 计算缩放前后鼠标位置的世界坐标
  const worldXBefore = (mouseX - offsetX.value) / scale.value;
  const worldYBefore = (mouseY - offsetY.value) / scale.value;

  // 应用新的缩放比例
  const oldScale = scale.value;
  scale.value = newScale;

  // 调整偏移量，使缩放后鼠标指向的世界坐标点保持不变
  offsetX.value = mouseX - worldXBefore * newScale;
  offsetY.value = mouseY - worldYBefore * newScale;

  // 应用边界限制
  constrainMapPosition();
};

// 鼠标按下开始拖动
const handleMouseDown = (event) => {
  isDragging.value = true;
  lastMouseX.value = event.clientX;
  lastMouseY.value = event.clientY;
  // 更改鼠标样式
  document.body.style.cursor = "grabbing";
};

// 鼠标移动时拖动地图
const handleMouseMove = (event) => {
  if (!isDragging.value) return;

  const deltaX = event.clientX - lastMouseX.value;
  const deltaY = event.clientY - lastMouseY.value;

  // 临时保存新的偏移值
  const tempOffsetX = offsetX.value + deltaX;
  const tempOffsetY = offsetY.value + deltaY;

  // 先应用临时偏移
  offsetX.value = tempOffsetX;
  offsetY.value = tempOffsetY;

  // 应用边界限制
  constrainMapPosition();

  lastMouseX.value = event.clientX;
  lastMouseY.value = event.clientY;
};

// 鼠标释放结束拖动
const handleMouseUp = () => {
  isDragging.value = false;
  // 恢复鼠标样式
  document.body.style.cursor = "default";
};

// 放大地图
const zoomIn = () => {
  if (scale.value < maxScale.value) {
    scale.value = Math.min(maxScale.value, scale.value + 0.5);
    // 应用边界限制
    constrainMapPosition();
  }
};

// 缩小地图
const zoomOut = () => {
  if (scale.value > minScale.value) {
    scale.value = Math.max(minScale.value, scale.value - 0.5);
    // 应用边界限制
    constrainMapPosition();
  }
};

// 重置地图缩放和平移
const resetZoom = () => {
  scale.value = 1;
  offsetX.value = 0;
  offsetY.value = 0;
};

</script>

  <style scoped>
.agv-position-container {
  padding: 2px;
}

.control-bar {
  margin-bottom: 4px;
  padding: 2px;
  background-color: #f5f5f5;
  border-radius: 4px;
}

.map-container {
  width: 100%;
  height: 85vh;
  margin-bottom: 2px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  overflow: hidden;
}

.map-area {
  width: 100%;
  height: 100%;
  position: relative;
  transform-origin: center center;
  cursor: grab;
}

.map-area:active {
  cursor: grabbing;
}

.map-background {
  width: 100%;
  height: 100%;
  background-color: #f9f9f9;
  background-image: linear-gradient(#e0e0e0 1px, transparent 1px), linear-gradient(90deg, #e0e0e0 1px, transparent 1px);
  background-size: 50px 50px;
  position: relative;
}

.station {
  position: absolute;
  width: 40px;
  height: 40px;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  transform-origin: center;
  transition: all 0.3s ease;
}

.station:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

/* 充电站点样式 */
.station-charging {
  background-color: #d10e9042;
  border-color: #d10e90;
}

/* 入库站点样式 */
.station-inbound {
  background-color: #f6ffed;
  border-color: #b7eb8f;
}

/* 出库站点样式 */
.station-outbound {
  background-color: #fff1f0;
  border-color: #ffccc7;
}

/* 分拣站点样式 */
.station-sorting {
  background-color: #fff7e6;
  border-color: #ffd591;
}

/* 维修站点样式 */
.station-maintenance {
  background-color: #f9f0ff;
  border-color: #d3adf7;
}

/* 未知类型站点样式 - 默认备用 */
.station-unknown {
  background-color: #f5f5f5;
  border-color: #d9d9d9;
}

.agv-marker {
  position: absolute;
  width: 30px;
  height: 30px;
  border-radius: 20%;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  transform-origin: center;
}

.agv-marker:hover {
  transform: translate(-50%, -50%) scale(1.2);
}

.data-table {
  margin-top: 2px;
}
</style>
